<template>
	<view>
		<scroll-view @scrolltolower="atBottom" scroll-y class="list" style="height: calc(100vh - 110px);">
			<view class="data-list" v-for="(item, index) in listData" :key="index" @click="toInfo(item)">
				<view class="data-item">
					<view class="item-text item-line item-title">
						<checkbox :checked="item.checked" style="transform:scale(0.8)" @click.stop="checkItem(item)"/>
						<text>{{item.taskName}}</text>
						<text class="green">({{$t('inspection.offline.offline')}})</text>
					</view>
					<view class="item-text item-line item-desc item-more">
						<view class="fixed-width">{{$t('baseCommon.time.startTime')}}</view>
						<view class="desc-val">{{item.planStartTime}}</view>
					</view>
					<view class="item-text item-line item-desc item-more">
						<view class="fixed-width">{{$t('baseCommon.time.endTime')}}</view>
						<view class="desc-val">{{item.planEndTime}}</view>
					</view>
					<view class="item-text item-line item-desc item-more">
						<view class="fixed-width">{{$t('baseCommon.status.state')}}</view>
						<view>
							<text :class="item.taskState == '2' ? 'orange' : 'green'" >{{item.taskState | codeFormat(statusList)}}</text>
						</view>
					</view>
				</view>
			</view>
			<view class="textcenter" v-if="isEnd">{{$t('baseCommon.message.noMoreData')}}</view>
		</scroll-view>
		
		<view class="buttombtn">
			<button type="primary" @click="submitTask">{{$t('inspection.offline.oneClickSubmit')}}</button>
			<button type="primary" @click="delTask">{{$t('inspection.offline.deleteTask')}}</button>
		</view>
		
		<uni-popup ref="popup" :mask-click="false">
			<task-progress :data="checkedList" @deleteTask="deleteOfflineTask" @close="closePop"></task-progress>
		</uni-popup>
	</view>
	
</template>

<script>
	import taskProgress from './progress.vue'
	import * as sqliteUtil from '@/utils/sqlite.js'
	import * as sqliteInspect from '@/utils/business/inspectSqlite.js'
	import { notice, utilities } from '@/utils/common.js'
	import { getTaskInfo, uploadTask } from '@/api/business/inspect.js'
	import { accessToken } from '@/api/platform/oauth.js'
	import { getNetwork, blueToothRestart } from '@/utils/device.js'
	import project from '@/utils/config/project.js'
	
	export default {
		components: {
			taskProgress
		},
		data() {
			return {
				statusList: [],
				listData: [],
				isEnd: false,
				checkedList: []
			}
		},
		mounted() {
			this.init()
		},
		methods: {
			init() {
				if(!sqliteUtil.isOpen()) {
					sqliteUtil.openSqlite()
				}
				
				sqliteUtil.selectTableInfo('m_ri_code', 'cat_no', 'DJ_TASK_STATE').then(res=>{
					this.statusList = []
					res.forEach(item=>{
						this.statusList.push({
							value: Number(item.cd_no),
							label: item.cd_name
						})
					})
				})
				
				this.atTop()
			},
			atBottom() {
				if (!this.isEnd) {
					this.loadData()
				}
			},
			atTop() {
				this.isEnd = false;
				this.listData = [];
				this.loadData();
			},
			loadData() {
				// 先建表，防止查询报错
				sqliteInspect.createMRiTask()
				sqliteInspect.createMRiTaskInfo()
				sqliteInspect.createMCpisAppCollectStatus()
				sqliteUtil.createMCpisFileAttachment()
				
				uni.showLoading({
					title: this.$t('common.loading')
				})
				sqliteUtil.selectTableInfo('m_ri_task').then(res=>{
					uni.hideLoading()
					
					if (res && res.length > 0) {
						// 下划线转驼峰
						utilities.formatHumpLineTransfer(res)
						this.listData = this.listData.concat(res);
						this.listData.forEach(item=>{
							item.checked = false
						})
						this.isEnd = true;
					} else {
						this.isEnd = true;
					}
				})
			},
			toInfo(item) {
				uni.navigateTo({
					url: "/pages/business/inspect/offline/inspectDetail?taskId=" + item.taskId
				})
			},
			checkItem(item) {
				item.checked = !item.checked
			},
			getCheckedList() {
				this.checkedList = []
				this.listData.forEach(item=>{
					if(item.checked) {
						this.checkedList.push(item)
					}
				})
			},
			async submitTask() {
				// 查询网络环境
				let netFlag = getNetwork()
				if(!netFlag) {
					notice.toast(this.$t('inspection.message.checkNetwork'))
					return
				}
				
				this.getCheckedList()
				if(this.checkedList.length === 0) {
					notice.toast(this.$t('baseCommon.message.pleaseSelect', { title: this.$t('inspection.taskPlan.taskPlan') }))
					return
				}
				
				uni.showLoading({
					title: this.$t('baseCommon.message.pleaseWait'),
					mask: true
				})
				// 申请token
				const param = {
					client_id: project.OFFLINE_CLIENT_ID,
					client_secret: project.OFFLINE_CLIENT_SECRET,
					grant_type: project.OFFLINE_GRANT_TYPE,
					username: ""
				}
				let tokenData = await accessToken(param)
				let token = tokenData.data.access_token
				uni.setStorageSync("_app_token", token)
				
				let flag = false
				let done = []
				for(const task of this.checkedList) {
					// 查询任务状态
					await getTaskInfo(task.taskId).then(res=>{
						// 完成或取消
						if(res.data.taskState == '3' || res.data.taskState == '-1') {
							flag = true
							done.push(task)
						}
					})
					if(flag) {
						break
					}
				}
				if(flag) {
					uni.hideLoading()
					let that = this
					uni.showModal({
						title: this.$t('baseCommon.message.tips'),
						content: '【'+done[0].taskName+'】' + this.$t('inspection.message.taskCompletedDelete'),
						success: function (res) {
							if(res.confirm) {
								that.deleteOfflineTask(done[0].taskId)
								that.atTop()
					        } else if (res.cancel) {
					            console.log('用户点击取消')
					        }
					    }
					});
				} else {
					uni.hideLoading()
					// 重启蓝牙
					blueToothRestart()
					this.$refs.popup.open()
				}
			},
			closePop() {
				this.$refs.popup.close()
				this.atTop()
			},
			delTask() {
				this.getCheckedList()
				if(this.checkedList.length === 0) {
					notice.toast(this.$t('baseCommon.message.pleaseSelect', { title: this.$t('inspection.taskPlan.taskPlan') }))
					return
				}
				if(this.checkedList.length > 1) {
					notice.toast(this.$t('inspection.message.onlyOneTask'))
					return
				}
				
				this.checkedList.forEach(async task=>{
					// 查询任务是否已有检查项执行了
					let flag = false
					await sqliteUtil.selectTableInfo('m_ri_task_inspection', 'task_id', task.taskId).then(res=>{
						for(let item of res) {
							if(item.exec_result != 'null') {
								flag = true
								break
							}
						}
					})
					
					if(flag) {
						const that = this
						uni.showModal({
							title: this.$t('baseCommon.message.tips'),
							content: this.$t('inspection.message.taskCheckedDelete'),
							success: async function (res) {
								if(res.confirm) {
									await that.deleteOfflineTask(task.taskId)
									that.atTop()
						        } else if (res.cancel) {
						            console.log('用户点击取消');
						        }
						    }
						});
					} else {
						await this.deleteOfflineTask(task.taskId)
						this.atTop()
					}
				})
			},
			async deleteOfflineTask(taskId) {
				// 删除巡检任务关联的附件
				let taskList = await sqliteUtil.selectTableInfo('m_ri_task', 'task_id', taskId)
				utilities.formatHumpLineTransfer(taskList)
				await this.deleteOfflineFile(taskList)
				
				// 删除 m_ri_task表数据
				await sqliteUtil.deleteTableInfo('m_ri_task', 'task_id', taskId)
				
				// 删除 m_ri_task_info表数据
				await sqliteUtil.deleteTableInfo('m_ri_task_info', 'task_id', taskId)
				
				// 查询检查项关联的缺陷
				let defectList = []
				let inspectList = await sqliteUtil.selectTableInfo('m_ri_task_inspection', 'task_id', taskId)
				utilities.formatHumpLineTransfer(inspectList)
				for(let i=0; i<inspectList.length; i++) {
					let item = inspectList[i]
					if(item.dfNo) {
						await sqliteUtil.selectTableInfo('m_df_information', 'df_id', item.dfNo).then(res=>{
							utilities.formatHumpLineTransfer(res)
							defectList.push(res[0])
						})
					}
				}
				
				// 删除巡检项关联的附件
				await this.deleteOfflineFile(inspectList)
				
				// 删除 m_ri_task_inspection表数据
				await sqliteUtil.deleteTableInfo('m_ri_task_inspection', 'task_id', taskId)
				
				// 删除缺陷关联的附件
				await this.deleteOfflineFile(defectList)
				
				// 删除 m_df_information表数据
				defectList.forEach(item => {
					sqliteUtil.deleteTableInfo('m_df_information', 'df_id', item.dfId)
				})
				
				// 删除 m_cpis_app_collect_status表数据
				await sqliteUtil.deleteTableInfo('m_cpis_app_collect_status')
			},
			async deleteOfflineFile(dataList) {
				for(let i=0; i<dataList.length; i++) {
					let item = dataList[i]
					if(item.attachFile && item.attachFile != "[]") {
						let files = item.attachFile.split(',')
						for(let j=0; j<files.length; j++) {
							sqliteUtil.deleteTableInfo('m_cpis_file_attachment', 'id', files[j])
						}
					}
				}
			}
		}
	}
</script>

<style lang="scss">
	@import '@/static/style/common-list.scss';
	
	.data-list {
		padding: 0 12px;
	}
	
	.item-line:last-of-type {
		border-bottom: 0;
	}
	
	.desc-val {
		color: #333;
	}
	
	.textcenter {
		padding: 5px 0;
		text-align: center;
	}
	
	.buttombtn {
		position: fixed;
		bottom: 10px;
		width: 100%;
		display: flex;
		
		uni-button {
			flex: 1;
			background-color: #1E91E6;
			margin: 0 8px;
			font-size: 16px;
			color: #FFFFFF;
		}
	}
</style>
